package com.ruoyi.mdkt.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.mdkt.entity.*;
import com.ruoyi.mdkt.entity.vo.CourseVo;
import com.ruoyi.mdkt.service.*;
import com.ruoyi.mdkt.utils.RankingUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gwl
 * @since 2022-10-22
 */
@Api(tags = "课程管理")
@CrossOrigin
@RestController
@RequestMapping("/mdkt/course")
public class CourseController extends BaseController {


    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseInfoService courseInfoService;
    @Autowired
    private CourseStudentService courseStudentService;
    @Autowired
    private RankingUtils rankingUtils;
    @Autowired
    private CourseDateService courseDateService;
    @Autowired
    private EventService eventService;

    @PostMapping("/findQueryPage/{pageNum}/{pageSize}")
    public R<Page<CourseVo>> pageList(@RequestBody(required = false) Course searchObj, @PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        Page<CourseVo> page = courseService.pageList(searchObj, pageNum, pageSize);
        return R.ok(page);
    }

    @DeleteMapping("/remove/{courseId}")
    public R remove(@PathVariable("courseId") Long courseId) {
        courseService.removeById(courseId);
        LambdaQueryWrapper<CourseStudent> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CourseStudent::getCourseId, courseId);
        courseStudentService.remove(lambdaQueryWrapper);
        return R.ok();
    }

    @DeleteMapping("/removeBatch")
    public R removeBatch(@RequestBody(required = false) ArrayList<Long> idList) {
        for (Long courseId : idList) {
            courseService.removeById(courseId);
            LambdaQueryWrapper<CourseStudent> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(CourseStudent::getCourseId, courseId);
            courseStudentService.remove(lambdaQueryWrapper);
        }
        return R.ok();
    }


    @GetMapping("/getClassing/{userId}")
    public R<Course> getClassing(@PathVariable("userId") Long userId) {
        Course course = courseService.getClassing(userId);
        return R.ok(course);
    }

    @GetMapping("/getNotClassing/{userId}")
    public R<List<Course>> getNotClassing(@PathVariable("userId") Long userId) {
        List<Course> courses = courseService.getNotClassing(userId);
        return R.ok(courses);
    }

//    @GetMapping("/pageByTeacherUserId")
//    @ResponseBody
//    public R pageByTeacherUserId(@RequestParam("teacherId") Collection<? extends Serializable>  teacherId){
//        List<Course> list=courseService.listByIds(teacherId);
//        Page page=courseService.page();
//        return R.ok(page);
//    }

    @GetMapping("/getCourseInfo/{courseId}")
    @ResponseBody
    public R getCourseInfo(Long courseId) {
        LambdaQueryWrapper<CourseInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CourseInfo::getCourseId, courseId);
        CourseInfo courseInfo = courseInfoService.getOne(lambdaQueryWrapper);
        return R.ok(courseInfo);
    }

    @GetMapping("/pageByTeacherUserId/{teacherUserId}")
    public R<Page> pageByTeacherUserId(@PathVariable("teacherUserId") Long teacherUserId, Integer pageSize, Integer pageNum) {
        return R.ok(courseService.pageByTeacherUserId(teacherUserId, pageSize, pageNum));
    }

    @GetMapping("/publishCourse/{courseId}")
    public R<String> publishCourse(@PathVariable("courseId") Long courseId) {
        courseService.publishCourse(courseId);
        return R.ok("发布课程成功");
    }

    @GetMapping("/getStudentName/{courseId}")
    public R<String> getStudentName(@PathVariable("courseId") Long courseId) {
        return R.ok(rankingUtils.getRandomName(courseId));
    }

    @GetMapping("/signCourseInfo/{teacherId}")
    public R signCourseInfo(@PathVariable("teacherId") Long teacherId) {
        LambdaQueryWrapper<Course> lambdaQueryWrapper = new LambdaQueryWrapper<Course>();
        lambdaQueryWrapper.eq(Course::getTeacherId, teacherId);
        Course course = courseService.getOne(lambdaQueryWrapper);
        return R.ok(course);
    }

    @GetMapping("/getStudentAllCourse/{userId}")
    public R getStudentAllCourse(@PathVariable("userId") Long userId) {
        LambdaQueryWrapper<CourseStudent> lambdaQueryWrapper = new LambdaQueryWrapper<CourseStudent>();
        lambdaQueryWrapper.eq(CourseStudent::getStudentUserId, userId);
        List<CourseStudent> list = courseStudentService.list(lambdaQueryWrapper);
        Course course = new Course();
        for (CourseStudent courseStudent : list) {
            LambdaQueryWrapper<Course> lambdaQueryWrapper1 = new LambdaQueryWrapper<Course>();
            lambdaQueryWrapper1.eq(Course::getId, courseStudent.getCourseId());
            course = courseService.getOne(lambdaQueryWrapper1);
        }
        return R.ok(course);
    }


    @PostMapping("/addCourse")
    public R addCourse(@RequestBody Course course) {
        courseService.save(course);
        return R.ok();
    }

    @PostMapping("/addClassHour")
    public R addClassHour(@RequestBody CourseDate courseDate) {
        courseDateService.save(courseDate);
        return R.ok("添加成功");
    }

    @GetMapping("/joinCourse/{joinCode}")
    public R joinCourse(@PathVariable("joinCode") String joinCode) throws IOException {
        BASE64Decoder base64Decoder = new BASE64Decoder();
        byte[] bytes = base64Decoder.decodeBuffer(joinCode);
        String courseId = new String(bytes, StandardCharsets.UTF_8);
        Course course = courseService.getById(courseId);
        if (course == null) {
            return R.fail("邀请码错误，课程不存在！");
        } else {
            CourseStudent courseStudent = new CourseStudent();
            courseStudent.setCourseId(course.getId());
            courseStudent.setStudentUserId(getUserId());
            if (courseStudentService.save(courseStudent)) {
                return R.ok();
            } else {
                return R.fail("加入课程失败");
            }
        }
    }

    @GetMapping("/getJoinCode/{courseId}")
    public R getJoinCode(@PathVariable("courseId") Long courseId) {
        Course course = courseService.getById(courseId);
        if (course == null) {
            return R.fail("课程不存在！");
        } else {
            String s = String.valueOf(courseId);
            BASE64Encoder base64Encoder = new BASE64Encoder();
            String joinCode = base64Encoder.encode(s.getBytes(StandardCharsets.UTF_8));
            return R.ok(joinCode);
        }
    }

    @GetMapping("/quitCourse/{courseId}/")
    public R quitCourse(@PathVariable("courseId") Long courseId) {
        LambdaQueryWrapper<CourseStudent> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CourseStudent::getCourseId, courseId).eq(CourseStudent::getStudentUserId, getUserId());
        boolean remove = courseStudentService.remove(lambdaQueryWrapper);
        if (remove == true) {
            return R.ok();
        } else {
            return R.fail("此课程不存在或用户不在此课程！");
        }
    }

    @GetMapping("/removeStudent/{userId}/{courseId}")
    public R removeStudent(@PathVariable("userId") Long userId, @PathVariable("courseId") Long courseId) {
        LambdaQueryWrapper<CourseStudent> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CourseStudent::getStudentUserId, userId).eq(CourseStudent::getCourseId, courseId);
        boolean remove = courseStudentService.remove(lambdaQueryWrapper);
        if (remove == true) {
            return R.ok();
        } else {
            return R.fail("此课程不存在或用户不在此课程！");
        }
    }

    @GetMapping("/getEvent/{courseId}")
    public R getEvent(@PathVariable("courseId") Long courseId) {
        return R.ok(eventService.getEventList(courseId));
    }

    @GetMapping("/createEvent/{courseId}")
    public R createEvent(@PathVariable("courseId") Long courseId) {
        return R.ok(eventService.createClassingEvent(courseId));
    }

    @GetMapping("/randomStudent/{courseId}")
    public R randomStudent(@PathVariable("courseId") Long courseId) {
        List<Student> studentInCourse = courseStudentService.getStudentInCourse(courseId);
        Random random = new Random();
        int i = random.nextInt(studentInCourse.size());
        return R.ok(studentInCourse.get(i));
    }
}

